import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormControl, FormGroup} from "@angular/forms";
import {Http} from "@angular/http";
import {ActivatedRoute} from "@angular/router";
import {DriverService} from "../../shared/service/driver.service";
import {UserTableComponent} from "../../shared/component/user-table/user-table.component";
import {FileUploadComponent} from "../../shared/component/file-upload/file-upload.component";
import {SingleOpenWinService} from "../../shared/service/single-open-win.service";
import {Driver} from "../../shared/model/driver";
import {FileUploadService} from "../../shared/service/file-upload.service";
declare var $:any;

@Component({
  selector: 'app-new-driver',
  templateUrl: './new-driver.component.html',
  styleUrls: ['./new-driver.component.css']
})
export class NewDriverComponent implements OnInit {

  radioValue:number;

  userId: string = this.routeInfo.snapshot.queryParams['userId'];
  driverForm: FormGroup;
  IDValidFlag:boolean = false;
  statusFlag:boolean = false;
  public searchParam: FormControl = new FormControl();
  @ViewChild(UserTableComponent) userTable :UserTableComponent;
  @ViewChild(FileUploadComponent) child :FileUploadComponent;

  //新增修改删除是否禁用标志
  btnDisabled:boolean = false;

  licenseTypes:any=[{
    "id":"A1",
    "name":"A1"
  },{
    "id":"A2",
    "name":"A2"
  },{
    "id":"A3",
    "name":"A3"
  },{
    "id":"B1",
    "name":"B1"
  },{
    "id":"B2",
    "name":"B2"
  },{
    "id":"C1",
    "name":"C1"
  },{
    "id":"C2",
    "name":"C2"
  },{
    "id":"C3",
    "name":"C3"
  },{
    "id":"C4",
    "name":"C4"
  },{
    "id":"D",
    "name":"D"
  },{
    "id":"E",
    "name":"E"
  },{
    "id":"F",
    "name":"F"
  },{
    "id":"M",
    "name":"M"
  },{
    "id":"N",
    "name":"N"
  },{
    "id":"P",
    "name":"P"
  }];

  //选择车辆类型分页
  _dataSet = [];
  _current = 1;
  _pageSize = 10;
  _total = 1;

  //存储table中全部数据
  driverData = [];

  _displayData: Array<any> = [];
  selected: any=[];

  constructor(private fb: FormBuilder,
              private http: Http,
              private routeInfo: ActivatedRoute,
              private driverService:DriverService,
              private singleOpenWinService:SingleOpenWinService,
              private FileUploadService:FileUploadService) {

  }

  ngOnInit() {

    this.createForm();

    this.getDatas();

    //初始化出生年月
    $('#birthdays').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      ignoreReadonly: true,
    });

    //初始化领证日期
    $('#certificationDates').datetimepicker({
      format: 'YYYY-MM-DD',
      locale: 'zh-cn',
      ignoreReadonly: true,
    });

    //订阅司机开窗
    this.singleOpenWinService.valueChange.subscribe((info:string)=>{
      // console.log("add");
      $('#id').val(this.userTable.selected.id);
      $('#name').val(this.userTable.selected.name);
      this.driverForm.patchValue({
        id:this.userTable.selected.id,
        name:this.userTable.selected.name
      });
      this.userIsVisible = false;
      this.toSearchId("openwin");
    });

  }

  //刷新数据
  refreshData(reset = false) {
    if (reset) {
      this._current = 1;
    }
    // this.getDatas();
  };


  //获取数据
  getDatas(){
    this.driverService.getDriverList().then(
      res => {
        this._dataSet = res;
        this.driverData = res;
      }
    );
  }

  //司机表格
  driverDisplayDataChange($event) {
    this._displayData = $event;
  };

  onSelect(data){
    this.selected = data;

    // this.FileUploadService.selectDataEvent.emit(data.oid);
   this.child.selectFileUpload(data.oid);

    this.driverForm.reset({
      oid:data.oid,
      id:data.id,
      name:data.name,
      birthday:data.birthday,
      gender:data.gender,
      phone:data.phone,
      licenseType:data.licenseType,
      certificationDate:data.certificationDate
    });

    this.statusFlag = true;
    this.btnDisabled = true;
    console.log( this.child.fileList);
  }

  updateInfo(val:any){
    if(this.checkFormData("update")){
      this.driverForm.patchValue({
        birthday:$('#birthday').val(),
        certificationDate:$('#certificationDate').val()
      });
      this.driverService.updateDriver(this.driverForm.value,this.child.fileoids).then(res=>{
        if(res.code ===1){
          alert(res.message);
          this.clearInfo();
          this.btnDisabled = false;
        }else{
          alert(res.message);
        }
      });
    }
  }

  onSubmit(val:any){
    if(this.checkFormData("add")){
      this.driverForm.patchValue({
        birthday:$('#birthday').val(),
        certificationDate:$('#certificationDate').val()
      });
      this.driverService.createDriver(this.driverForm.value,this.child.fileoids).then(res=>{
        if(res.code ===1){
          alert(res.message);
          this.clearInfo();
        }else{
          alert(res.message);
        }
      });
    }

  }

  //判断是否有重复ID
  toSearchId(str){
    if(!this.statusFlag) {
      let pid = this.driverForm.get('id').value.replace(/^\s+|\s+$/g, "");
      if (pid.length != 0) {
        this.driverService.checkDriverByID(pid)
          .then(res => {
            if (res.code === 1) {
              alert("司机代号已存在，请重新输入！");
              if (str != "openwin") {
                this.driverForm.patchValue({
                  id: '',
                });
              } else {
                this.driverForm.patchValue({
                  id: '',
                  name: '',
                });
              }
              this.IDValidFlag = false;
            } else {
              this.IDValidFlag = true;
            }
          });
      }
    }
  }

  //查询
  searchInfo(){
    let result = this.driverData;
    result = result.filter((f: Driver) => f.name.indexOf(this.searchParam.value) !== -1);
    this._dataSet = result;
  }

  //删除
  delType():void {
    if(this.selected.oid != "" && this.selected.oid != undefined){
      if(confirm("确认删除?")){
        this.driverService.deleteDriver(this.selected.oid).then(
          res => {
            if(res.code > 0){
              alert(res.message);
              this.clearInfo();
              this.btnDisabled = false;
            }
          }
        )
      }
    }else{
      alert("请选择一条要删除的数据！\n");
    }

  }

  //清空表格
  clear(){
    this.driverForm.reset({
      oid:'',
      id: '',
      name: '',
      birthday: '',
      gender: '',
      phone: '',
      licenseType: '',
      certificationDate: '',
      creator:this.userId
    });
    this.selected = [];
    this.statusFlag = false;
    this.btnDisabled = false;
    this.child.fileList = [];
  }

  //清空查询条件
  clearParam(){
    $("#searchpa").val("");
    this.searchParam.reset("");
  }

  //初始化form
  createForm(){
    this.driverForm =this.fb.group({
      oid:'',
      id: '',
      name: '',
      birthday: '',
      gender: '',
      phone: '',
      licenseType: '',
      certificationDate: '',
      creator:this.userId
    });
  }

  /**
   *  单选人员开窗
   */
  userIsVisible = false;

  userShowModal = () => {
    this.userIsVisible = true;
  }

  userHandleCancel = (e) => {
    this.userIsVisible = false;
  }

  //司机信息开窗
  driverOpenWin(){
    this.userShowModal();
  }

  //验证表单
  checkFormData(str){
    //ID重复则不进行下面的判断
    if(!this.IDValidFlag&&this.driverForm.get("id").value&&str == "add"){
      return false;
    }else {
      let msg = "";
      let regexp = /^0\d{2,3}-[1-9]\d{6,7}$|^[1][3,4,5,7,8][0-9]{9}$/;  //判断为电话号码
      if (!this.driverForm.get("id").value.replace(/^\s+|\s+$/g,"")) {
        msg += ("请输入司机代号\n");
      }
      if (!this.driverForm.get("name").value.replace(/^\s+|\s+$/g,"")) {
        msg += ("请输入司机名称\n");
      }
      if (typeof(this.driverForm.get("gender").value) == "undefined") {
        msg += ("请选择司机性别\n");
      }
      if (!this.driverForm.get("phone").value.replace(/^\s+|\s+$/g,"")) {
        msg += ("请输入电话号码\n");
      }
      if (this.driverForm.get("phone").value && !regexp.test(this.driverForm.get("phone").value)) {
        msg += ("请输入有效的电话号码\n");
      }
      if (!this.driverForm.get("licenseType").value) {
        msg += ("请选择准驾车型\n");
      }
      if (msg) {
        alert(msg);
        return false;
      } else {
        return true;
      }
    }
  }

  //新增修改删除数据后，刷新表格，清空表单
  clearInfo(){
    this.driverForm.reset({
      oid:'',
      id: '',
      name: '',
      birthday: '',
      gender: '',
      phone: '',
      licenseType: '',
      certificationDate: '',
      creator:this.userId
    });
    this.statusFlag = false;
    this.selected = [];
    this.getDatas();
    this.refreshData(true);
    this.clearParam();
    //清空附件列表信息
    this.child.fileList = [];
  }

}
